<template>
    <div class="list">
        <ul>
            <li class="letter"
            v-for="item of letters"
            :key="item"
            :ref="item"
            @click="handleLetterClick"
            @touchstart.prevent="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
              >{{item}}</li>
        </ul>
    </div>
</template>

<script>
export default {
  name: 'Alphabet',
  props: {
    areaCity: Object
  },
  data () {
    return {
      touchStarts: false,
      startY: 0,
      // 节流，提升性能
      timer: null
    }
  },
  updated () {
    // 性能提升
    this.startY = this.$refs['A'][0].offsetTop
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.areaCity) {
        letters.push(i)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (e) {
      // console.log(e.target.innerText)
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStarts = true
    },
    handleTouchMove (e) {
      if (this.touchStarts) {
        // const startY = this.$refs['A'][0].offsetTop
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79 // 手指距离顶部的高度，79为头部高度
          const indexY = Math.floor((touchY - this.startY) / 22)
          if (indexY >= 0 && indexY < this.letters.length) {
            this.$emit('change', this.letters[indexY])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStarts = false
    }
  }
}
</script>

<style scoped>
    .list{
        display:flex;
        flex-direction: column;
        justify-content: center;
        position: absolute;
        top: 6rem;
        bottom: 0;
        right: 0px;
        width: 4rem;
        color: #000;
        font-size: 1rem;
    }
    .list ul{
        list-style-type: none;
    }
    .list .letter{
        text-align: center;
        height: 1.4rem;
        color: #00bcd4;
        font-weight: 600;
    }
</style>
